from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.modules.bank_card import BankCard
from comment.modules.user import User
from comment.modules import db
from comment.utils.decrators import login_required

class Crad_Resource(Resource):
    '''
    银行卡管理的资源类
    '''
    # 登录拦截器
    method_decorators = [login_required]

    def post(self):
        uid=g.user_id
        login_user = User.query.filter(User.id == uid).first()


        rp = RequestParser()
        rp.add_argument('holder', required=True)  # 持卡人（账户名字）
        rp.add_argument('openingBank', required=True)  # 开户银行
        rp.add_argument('bankBranch', required=True)  # 支行
        rp.add_argument('cityId', required=True)  # 城市id
        rp.add_argument('cardNum', required=True)  # 卡片号码

        args = rp.parse_args()

        holder = args.holder
        opening_bank = args.openingBank
        bank_branch = args.bankBranch
        city_id = args.cityId
        bank_card_num = args.cardNum

        #验证银行卡号，是否唯一
        card_info = BankCard.query.filter(BankCard.bankCardNum == bank_card_num).first()
        if card_info:
            return {'message':'银行卡已经存在，请勿添加','code':20001}

        #把银行卡数据保存到数据库
        card = BankCard(bankCardNum=bank_card_num,openingBank=opening_bank,holder=holder,
                 bankBranch=bank_branch,cityId=city_id,userId=uid,reservePhone=login_user.phone)

        db.session.add(card)
        db.session.commit()
        return {'msg':'Success !!'}

    def get(self):
        '''
        查询当前登录用户所拥有的银行卡列表
        :return:
        '''
        uid = g.user_id
        #查询数据库中的，当前用户中的银行卡
        card_list = BankCard.query.filter(BankCard.userId == uid).all()
        from financial.resource.card.serializers import  BankCardListSerializer
        if card_list:# 把对象转换成字典数据
            return  BankCardListSerializer(card_list).to_dict()
        else:
            return {}